package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.service.AdminService;
import com.qf.service.RoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

/*
 *@Description:
 *@author:刘哥
 *@Date:13:16 2022/7/25
 */
public class AdminAuthorizingRealm extends AuthorizingRealm {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;

    //  授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        DtsAdmin admin=(DtsAdmin)getAvailablePrincipal(principalCollection);
        Integer[] roleIds = admin.getRoleIds();
        Set<String> roleSet=roleService.queryRoles(roleIds);

        return null;
    }
//认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String pwd = new String(token.getPassword());
//        根据用户名到数据库中查询对应的用户对象
        List<DtsAdmin> adminList = adminService.findAdminByName(username);
//        判断查询结果是否正确
        if(adminList==null||adminList.size()==0){
            throw new UnknownAccountException("找不到用户,用户名有误");
        }
//        判断密码是否正确
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(!encoder.matches(pwd,adminList.get(0).getPassword())){
            throw new UnknownAccountException("密码不正确");
        }
//        封装查询到的用户给shiro框架处理
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,pwd,this.getName());
        return info;
    }
}
